By the end of this practical you will know how to:
.Rmd)| Package | Installation |
|---|---|
tidyverse |
install.packages("tidyverse") |
knitr |
install.packages("knitr") |
DT |
install.packages("DT") |
broom |
install.packages("broom") |
rmdformats |
install.packages("rmdformats") |
xaringan |
install.packages("xaringan") |
| File | Rows | Columns |
|---|---|---|
| mcdonalds.csv | 260 | 24 |
Open your R project. It should already have the folders 0_Data and 1_Code. Make sure that the data files listed in the Datasets section above are in your 1_Data folder
Because R Markdown looks quite a bit different from standard R code, the best way to look at examples is to see a new R Markdown document in action. In RStudio, click File – New File – R Markdown
Save your markdown file in your main project directory (not in the 4_Markdown folder! – you’ll put it there later!) under the name mcdonalds.Rmd
Now knit your document to an HTML file. To do this, click the knit button (or use the Command + Shift + K shortcut)
setup label. Inside of this chunk, write the comment # Load Packages -------------. Then, using the library() function, load the packages listed in the Packages section above.Knit your document! Make sure you don’t get any errors!
Now it’s time to load your datafiles. In the same setup chunk, load each of the data files listed in the Datasets section.
# --- Load packages
library(XX)
library(XX)
# --- Load data
XXX <- read_csv()
XXX <- read_csv()
Knit your document! Make sure you don’t get any errors!
Now it’s time to change some of the default chunk options. In your setup chunk, change the existing values of knitr::opts_chunk$set to the following:
# INCLUDE ALL OF THIS CODE IN YOUR FIRST CHUNK!
knitr::opts_chunk$set(fig.width = 6, # Figure width (in)
fig.height = 4, # Figure height (in)
echo = FALSE, # Repeat code
eval = TRUE, # Evaluate chunks
message = FALSE, # Don't print messages
warning = FALSE, # Don't print warnings
fig.align = 'center') # Center figures
options(digits = 2) # Round all output to 2 digits
Create a new first level header with the text “McDonalds” using a single hashtag
Knit the document!
You can find the McDonalds logo on wikipedia at the following link: https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/McDonald%27s_Golden_Arches.svg/2000px-McDonald%27s_Golden_Arches.svg.png. Using the include_graphics() function, include this image in your document (To make the image a bit smaller, include the chunk argument out.width = "30%")
include_graphics("https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/McDonald%27s_Golden_Arches.svg/2000px-McDonald%27s_Golden_Arches.svg.png")
mcdonalds object! You can get the number of columns with ncol(mcdonalds) and the number of rows with nrow(mcdonalds)mcdonalds data has 24 columns and 260 rows. Each row corresponds to a different menu item. The data originally come from Kaggle.datatable()Create a new code chunk by either clicking the “Insert - R” button, or by using the “Command + Option + I”" shortcut on Mac
Inside the chunk, include the following code which uses the datatable function to render a dataframe as a nicely formatted HTML table.
datatable(mcdonalds %>% select(1:6))
ggplot2 code that might help!)ggplot(data = mcdonalds,
aes(x = XX)) +
geom_histogram(col = "white") +
labs(title = "XX",
subtitle = "XX",
caption = "XX") +
theme_bw()
Knit the document! Diagnose and correct any errors!
Write the appropriate combination of markdown, text, and code to create the following output (Here’s some ggplot2 code that might help!):
ggplot(data = XX,
aes(x = XX, y = XX)) +
geom_point() +
labs(title = "XX",
subtitle = "XX",
caption = "XX") +
theme_bw()
Now let’s show the results of a regression analysis predicting the sodium content of an item as a function of its calories.
cal_sod_lm that is the result of a regression analysis predicting Sodium as a function of Calories. Use the following template# Create regression model predicting Sodium from Calories
cal_sod_lm <- lm(formula = XX ~ XX,
data = mcdonalds)
# Export cal_sod_lm to a nicely formatted table
kable(x = tidy(cal_sod_lm),
digits = 3,
caption = "Regression analysis predicting Sodium from Calories")
ggplot(data = mcdonalds,
aes(x = XX, y = XX, fill = XX)) +
stat_summary(geom = "bar", fun.y = "mean") +
guides(fill = FALSE) +
labs(title = "McDonalds Menu Items",
subtitle = "Created with ggplot2",
caption = "Source: Kaggle.com") +
theme_bw()
Knit the document! Diagnose and correct any errors!
Add the appropriate code to add the following output.
Calories_agg <- XX %>%
group_by(XX) %>%
summarise(
Min = min(Calories),
Mean = mean(Calories),
Median = median(Calories),
Max = max(Calories)
)
kable(x = XX,
caption = "XX")
Now it’s time to move your Markdown file to your 4_Markdown folder. Move your speffanalysis.Rmd file to your 4_Markdown folder using your computer file browser (Finder on Mac, Windows explorer on PC). Now, try knitting your document. You should get an error! What happened?!
The problem is that when you knit your Markdown file, R changes your working directory to the folder where your markdown file is located. However, now that you moved your file to your 4_Markdown folder, this isn’t true anymore. You need to tell Markdown that the root directory of your project is one directory up! Thankfully this is easy to do. Just add the following code to your initial setup R chunk:
# Tell R Markdown that the root directory is now one folder
# up from the folder the markdown file is in
knitr::opts_knit$set(root.dir = "../")
rmdformats package. Install the package with rmdformats. Then create a new markdown file from one of the temples with File – New File – R Markdown – From Template. Try the HTML readthedown template. Knit the document and see how it looks different from your standard template.Now it’s time to create a slideshow! To do this, we’ll use the Ninja template (click here for a demo) from the xaringan package (that’s what we use for all of our BaselRBootcamp slides). Install the xaringan package by running install.packages('xaringan')
Once you’ve installed xaringan, open a new template with File – New File – R Markdown – From Template – Ninja Presentation. Give the presentation a title and your name as the author. Then click ok.
You should see a new .Rmd document open. Save the document in your main project directory as slideshow.Rmd.
Knit the document to see the outline of the presentation!
Play around with the presentation a bit. Change the existing content a bit and add a few slides. Try adding an image (maybe this one: https://actgnetwork.org/sites/all/themes/actg/images/actg_logo_275.png) by saving the image to your 0_Materials folder, and then loading the image into your document with include_graphics().
Now, try to customize the presentation to include all of main analyses, outputs, and plots you have in your speffanalysis.Rmd document! Of course, there won’t be room for all of the text, so treat it like a normal presentation and put in what’s important.
Want to see the .Rmd file that created this practical? You can find it here.
The rmdformats package has many nice templates for .Rmd files. Look at their GitHub page at https://github.com/juba/rmdformats for examples. If you install the package from CRAN with install.packages('rmdformats'), you’ll get lots of new templates when you open a new Markdown file in RStudio.
If you want to use custom .css files, check out the the R Studio HTML document guide. You can also look at the .css files underlying the rmdformats package on their GitHub page here https://github.com/juba/rmdformats. For example, here is their .css file for the “html docco” template https://raw.githubusercontent.com/juba/rmdformats/master/inst/templates/html_docco/docco.css